package com.ruoyi.system.outto.goods.impl;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.ImgUntil;
import com.ruoyi.common.utils.ImgUntilYS;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.V2.gameAttr.mapper.GameAttrTemplateMapper;
import com.ruoyi.system.V2.gameAttr.mapper.GameAttributeMapper;
import com.ruoyi.system.V2.goodInfo.mapper.GoodsInfoImgMapper;
import com.ruoyi.system.V2.inter.mapper.ArtRecMapper;
import com.ruoyi.system.interAttr.domain.InterAttr;
import com.ruoyi.system.interAttr.mapper.InterAttrMapper;
import com.ruoyi.system.model.domain.*;
import com.ruoyi.system.model.dto.GoodsInfoAndAttrValueDto;
import com.ruoyi.system.outto.core.MapUntils;
import com.ruoyi.system.outto.goods.YISHOUYOUAPI;
import com.ruoyi.system.outto.goods.YSYAPI;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.net.CacheRequest;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author lz
 * @version 1.0
 * @date 2022/6/5 16:19
 */
@Slf4j
@Service
public class YISHOUYOUAPIImpl implements YISHOUYOUAPI {
    @Resource
    private GoodsInfoImgMapper goodsInfoImgMapper;
    @Resource
    private GameAttributeMapper gameAttributeMapper;
    @Value("${desc.title}")
    private String descTitle;
    @Resource
    private InterAttrMapper interAttrMapper;
    @Resource
    private GameAttrTemplateMapper gameAttrTemplateMapper;
    @Resource
    private ArtRecMapper artRecMapper;
    @Override
    public AjaxResult addGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, SalePartner salePartner) {
        Map<String, Object> result = new HashMap<>();
        Map<String, Object> params = params(goodsInfoAndAttrValueDto,salePartner);
        log.info("易手游添加接口请求参数={}", JSONObject.toJSONString(params));

        String response = HttpRequest.post("https://www.swcbg.com/api/User/publishShopNew").body(JSONObject.toJSONString(params)).execute().body();
        log.info("易手游添加接口返回参数={}", response);
        JSONObject resultJson = null;
        try {
            resultJson = JSONObject.parseObject(response);
        }catch (Exception e){
            throw new GlobalException(response);
        }
        if (!"1".equals(resultJson.getString("status"))) {
            result.put("code", 500);
        } else {
            result.put("code", 200);
            String shop_id = JSONObject.parseObject(resultJson.getString("data")).getString("shop_id");
            result.put("outId", shop_id);
        }
        result.put("msg", resultJson.getString("info"));
        result.put("req", JSONObject.toJSONString(params));
        result.put("res", response);
        return AjaxResult.success(result);
    }

    @Override
    public AjaxResult editGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, SalePartner salePartner) {
        Map<String, Object> result = new HashMap<>();
        Map<String, Object> params = new TreeMap<>();
        params.put("token",salePartner.getTwoOther());
        ArtRec artRecreq = new ArtRec();
        artRecreq.setConfig(salePartner.getId());
        artRecreq.setAccountId(goodsInfoAndAttrValueDto.getId());
        List<ArtRec> artRecs = artRecMapper.selectArtRecList(artRecreq);
        ArtRec artRec = artRecs.get(0);
        params.put("shop_id", artRec.getOutid());
        params.put("price", goodsInfoAndAttrValueDto.getPrice());
        log.info("易手游编辑接口请求参数={}", JSONObject.toJSONString(params));
        String response = HttpRequest.post("https://www.swcbg.com/api/User/setShopPrice").body(JSONObject.toJSONString(params)).execute().body();
        log.info("易手游编辑接口返回参数={}", response);
        JSONObject resultJson = JSONObject.parseObject(response);
        if (!"1".equals(resultJson.getString("status"))) {
            result.put("code", 500);
        } else {
            result.put("code", 200);
        }
        result.put("msg", resultJson.getString("info"));
        result.put("req", JSONObject.toJSONString(params));
        result.put("res", response);
        return AjaxResult.success(result);
    }

    private List<GameAttribute> getGameAttributs(String ids) {
        if (StringUtils.isEmpty(ids)) {
            return new ArrayList<>();
        }
        return gameAttributeMapper.selectGameAttributeListByIds((Long[]) ConvertUtils.convert(ids.split(","),
                Long.class));
    }

    private String reIds(String allIds, String ids) {
        if (StringUtils.isNotEmpty(ids)) {
            if (StringUtils.isNotEmpty(allIds)) {
                allIds = allIds + "," + ids;
            } else {
                allIds = ids;
            }
        }
        return allIds;
    }

    private void builderCheckAttr(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto,String checkAttr,Map<String,Object> form_data,Map<String,Object> form_info) {
        /**
         * 1、先查询自定义中所有多选的字段
         * 2、再查该账号单选字段中的选项
         * 3、再去接口属性匹配表过滤
         */
        Field[] declaredFields = goodsInfoAndAttrValueDto.getClass().getDeclaredFields();
        JSONObject checkAttrJson = JSONObject.parseObject(checkAttr);
        String interCheckBoxReqs = checkAttrJson.getString("interCheckBoxReqs");
        List<JSONObject> checkJsonList = JSONObject.parseArray(interCheckBoxReqs, JSONObject.class);
        if (org.springframework.util.CollectionUtils.isEmpty(checkAttrJson)) {
            throw new GlobalException("接口多选属性暂未配置");
        }

        GameAttrTemplate gameAttrTemplate = new GameAttrTemplate();
        gameAttrTemplate.setGameId(goodsInfoAndAttrValueDto.getGameId());
        gameAttrTemplate.setIsEnable("0");
        List<String> types = new ArrayList<>();
        types.add("checkbox");
        types.add("boxradio");
        gameAttrTemplate.setFieldTypes(types);
        List<GameAttrTemplate> checkAttrTemplates = gameAttrTemplateMapper.selectGameAttrTemplateList(gameAttrTemplate);

        for (JSONObject object : checkJsonList) {
            String string = "";
            String InterConfigId = object.getString("InterConfigId");
            for (GameAttrTemplate attrTemplate : checkAttrTemplates) {
                String aavName = attrTemplate.getAavName();
                for (Field declaredField : declaredFields) {
                    String name = declaredField.getName();
                    if (aavName.equals(name)) {
                        declaredField.setAccessible(true);

                        String ydConfigIdLeveOne = object.getString("YdConfigId");
                        if (StringUtils.isNotEmpty(ydConfigIdLeveOne)) {

                            String[] split2 = ydConfigIdLeveOne.split(",");
                            List<String> list2 = new ArrayList<>();
                            for (String s : split2) {
                                s = s.replace(" ", "");
                                list2.add(s);
                            }
                            if (list2.contains(attrTemplate.getId() + "")) {
                                Object o = null;
                                try {
                                    o = declaredField.get(goodsInfoAndAttrValueDto);
                                } catch (IllegalAccessException e) {
                                    throw new GlobalException("多选项" + attrTemplate.getFieldName() + "匹配错误");
                                }
                                String oneValue = String.valueOf(o);
                                if (StringUtils.isNotEmpty(ydConfigIdLeveOne)) {
                                    //一级属性已经匹配，开始匹配二级属性
                                    if (list2.contains(attrTemplate.getId() + "")) {
                                        String interCheckBoxReqsStr = object.getString("interCheckBoxReqs");
//                                        String interCheckBoxReqsStr = object.getString("interServerRes");
                                        //开始匹配二级属性
                                        List<JSONObject> jsonObjects2 = JSONObject.parseArray(interCheckBoxReqsStr, JSONObject.class);
                                        /**
                                         * 咱们的f字段  多选项都是用空格 隔开，用,号切割数组，跟匹配的数据匹配、匹配上说明此账号勾选的有此属性
                                         */
                                        for (JSONObject jsonObject1 : jsonObjects2) {
                                            if (StringUtils.isNotEmpty(oneValue)&&!oneValue.equals("null")) {
                                                String[] split1 = oneValue.split(",");
                                                String ydConfigId1 = jsonObject1.getString("YdConfigId");
                                                if(StringUtils.isNotEmpty(ydConfigId1)) {
                                                    ydConfigId1 = ydConfigId1.replace(" " , "");
                                                }
                                                for (String s : split1) {
                                                    if (Objects.equals(s, ydConfigId1)) {
                                                        String InterConfigId2 = jsonObject1.getString("InterConfigId");
                                                        string+=","+InterConfigId2;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                } else {
                                    throw new GlobalException("属性参数错误，请匹配后重新配置");
                                }
                            }
                        }
                    }
                }
            }
            if(StringUtils.isNotEmpty(string)){
                form_data.put(InterConfigId, string.substring(1));
                form_info.put(InterConfigId, string.substring(1));
            }
        }
        //========================多选属性匹配完成=====================//
    }

    /**
     * 开始匹配区服属性
     *
     * @param goodsInfoAndAttrValueDto
     * @param server
     */
    private void builderServer(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto,Map<String,Object> form_data, String server) {
        //========================开始匹配区服属性=====================//
        JSONObject jsonObject = JSONObject.parseObject(server);
        //开始匹配一级区服
        String interServeReqs = jsonObject.getString("interServeReqs");
        String qufuid = "";
        JSONObject oneServerJson = new JSONObject();
        List<JSONObject> oneServer = JSONObject.parseArray(interServeReqs, JSONObject.class);
        String gameClientId = "";
        String gameServerId = "";
        if (Objects.equals(goodsInfoAndAttrValueDto.getGameType(), "0")) {
            qufuid = goodsInfoAndAttrValueDto.getSystemId() + ""+goodsInfoAndAttrValueDto.getCarrierId() + "";
            for (JSONObject object : oneServer) {
                String ydServeId = object.getString("YdServeId");
                if(StringUtils.isNotEmpty(ydServeId)) {
                    ydServeId = ydServeId.replace(" ", "").replace(",", "");
                    if (ydServeId.equals(qufuid)) {
                        gameClientId = object.getString("id");
                        form_data.put("client", gameClientId);
                        qufuid = goodsInfoAndAttrValueDto.getSystemId() + "" + goodsInfoAndAttrValueDto.getCarrierId() + "";
                        if (goodsInfoAndAttrValueDto.getGameName().equals("永劫无间手游")) {
                            qufuid = goodsInfoAndAttrValueDto.getCarrierId() + "";
                        } else if (goodsInfoAndAttrValueDto.getGameName().equals("英雄联盟(手游)")) {
                            qufuid = goodsInfoAndAttrValueDto.getSystemId() + "" + goodsInfoAndAttrValueDto.getCarrierId() + "";
                        } else if (goodsInfoAndAttrValueDto.getGameName().equals("使命召唤手游")) {
                            qufuid = goodsInfoAndAttrValueDto.getCarrierId() + "";
                        } else if (goodsInfoAndAttrValueDto.getGameName().equals("王者荣耀")) {
                            qufuid = goodsInfoAndAttrValueDto.getSystemId() + "" + goodsInfoAndAttrValueDto.getCarrierId() + "";
                        } else if (goodsInfoAndAttrValueDto.getGameName().equals("三角洲行动")) {
                            qufuid = goodsInfoAndAttrValueDto.getCarrierId() + "";
                        }
                        String interServerRes = object.getString("interServerRes");
                        if (StringUtils.isNotEmpty(interServerRes)) {
                            oneServer = JSONObject.parseArray(interServerRes, JSONObject.class);
                            for (JSONObject objects : oneServer) {
                                String ydServeIds = objects.getString("YdServeId");
                                if (StringUtils.isNotEmpty(ydServeIds)) {
                                    ydServeIds = ydServeIds.replace(",", "").replace(" ", "");
                                    if (ydServeIds.contains(qufuid)) {
                                        gameServerId = objects.getString("id");
                                        form_data.put("server", gameServerId);
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        else if(goodsInfoAndAttrValueDto.getGameName().equals("无畏契约")){
            for (JSONObject object : oneServer) {
                String ydServeId = object.getString("YdServeId");
                if (StringUtils.isNotEmpty(ydServeId)) {
                    ydServeId = ydServeId.replace(",", "").replace(" ", "");
                    if (ydServeId.contains(qufuid)) {
                        gameClientId = object.getString("id");
                        String interServerRes = object.getString("interServerRes");
                        qufuid = goodsInfoAndAttrValueDto.getGroupId()+"";
                        oneServer = JSONObject.parseArray(interServerRes, JSONObject.class);
                        for(JSONObject objects : oneServer){
                            String ydServeIds = objects.getString("YdServeId");
                            ydServeIds = ydServeIds.replace(",", "").replace(" ", "");
                            if (Objects.equals(qufuid, ydServeIds)) {
                                gameServerId = objects.getString("id");
                                break;
                            }
                        }
                    }
                }
            }
        }
        else {
            qufuid = goodsInfoAndAttrValueDto.getGroupId()+"";;
            for (JSONObject object : oneServer) {
                String ydServeId = object.getString("YdServeId");
                if (StringUtils.isNotEmpty(ydServeId)) {
                    ydServeId = ydServeId.replace(",", "").replace(" ", "");
                    if (Objects.equals(qufuid, ydServeId)) {
                        gameClientId = object.getString("id");
                        form_data.put("client", gameClientId);
                        String interServerRes = object.getString("interServerRes");
                        qufuid = goodsInfoAndAttrValueDto.getServerId()+"";
                        oneServer = JSONObject.parseArray(interServerRes, JSONObject.class);
                        for(JSONObject objects : oneServer){
                            String ydServeIds = objects.getString("YdServeId");
                            ydServeIds = ydServeIds.replace(",", "").replace(" ", "");
                            if (ydServeIds.contains(qufuid)) {
                                gameServerId = objects.getString("id");
                                form_data.put("server", gameServerId);
                                break;
                            }
                        }
                    }
                }
            }
        }
    }
    private void builderRadioAttr(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, String radioAttr,Map<String,Object> form_data, Map<String,Object> form_info) {
        //========================开始匹配单选属性=====================//
        JSONObject jsonObject = JSONObject.parseObject(radioAttr);
        String interRadioReqs = jsonObject.getString("interRadioReqs");
        log.info(JSONObject.toJSONString(interRadioReqs));
        List<JSONObject> jsonObjects = JSONObject.parseArray(interRadioReqs, JSONObject.class);
        if (!org.springframework.util.CollectionUtils.isEmpty(jsonObjects)) {
            /**
             * 1、先查询自定义中所有单选的字段
             * 2、再查该账号单选字段中的选项
             * 3、再去接口属性匹配表过滤
             */
            GameAttrTemplate gameAttrTemplate = new GameAttrTemplate();
            gameAttrTemplate.setGameId(goodsInfoAndAttrValueDto.getGameId());
            gameAttrTemplate.setIsEnable("0");
            gameAttrTemplate.setFieldType("radio");
            List<GameAttrTemplate> gameAttrTemplates = gameAttrTemplateMapper.selectGameAttrTemplateList(gameAttrTemplate);
            Field[] declaredFields = goodsInfoAndAttrValueDto.getClass().getDeclaredFields();


            List<JSONObject> defObjects = new ArrayList<>();
            defObjects.addAll(jsonObjects);
            for (JSONObject object : jsonObjects) {
                if(object.getString("id").equals("该游戏没有该匹配项 保存即可！")){
                    return;
                }
                for (GameAttrTemplate attrTemplate : gameAttrTemplates) {
                    String aavName = attrTemplate.getAavName();
                    for (Field declaredField : declaredFields) {
                        String name = declaredField.getName();
                        if (aavName.equals(name)) {
                            //一级属性
                            //注意 YdConfigId 对应的是 f字段对应的 id
                            if (Objects.equals(object.getLong("YdConfigId"), attrTemplate.getId())) {
                                String InterConfigId = object.getString("InterConfigId");
                                defObjects.remove(object);//如果匹配上，则去掉
                                String interRadioReqs1 = object.getString("interRadioReqs");
                                List<JSONObject> jsonObjects2 = JSONObject.parseArray(interRadioReqs1, JSONObject.class);
                                declaredField.setAccessible(true);
                                try {
                                    //获取选择的值 例如  实名中的可二次
                                    Object o = declaredField.get(goodsInfoAndAttrValueDto);
                                    String oneValue = String.valueOf(o);
                                    List<JSONObject> twoAttr = jsonObjects2.stream().filter(j -> Objects.equals(j.getString("YdConfigId"), oneValue)).collect(Collectors.toList());
                                    String defaultValue = object.getString("defaultValue");
                                    if (org.springframework.util.CollectionUtils.isEmpty(twoAttr)) {
                                        if (StringUtils.isNotEmpty(defaultValue)) {
                                            String interServerRes = object.getString("interServerRes");
                                            List<JSONObject> interServerResss = JSONObject.parseArray(interServerRes, JSONObject.class);
                                            for(JSONObject jsonObject1 : interServerResss) {
                                                form_data.put(object.getString("id"),jsonObject1.getString("id"));
                                                form_info.put(object.getString("id"),jsonObject1.getString("id"));
                                            }
                                        }
                                    }
                                    if (!org.springframework.util.CollectionUtils.isEmpty(twoAttr)) {
                                        JSONObject jsonObject2 = twoAttr.get(0);
                                        form_data.put(object.getString("id"),jsonObject2.getString("id"));
                                        form_info.put(object.getString("id"),jsonObject2.getString("id"));
                                    }
                                } catch (Exception e) {
                                    throw new GlobalException("单选项" + attrTemplate.getFieldName() + "匹配错误");
                                }
                            }
                        }
                    }
                }
            }
            //开始匹配默认值
            for (JSONObject object : defObjects) {
                interRadioReqs = object.getString("interRadioReqs");
                jsonObjects = JSONObject.parseArray(interRadioReqs, JSONObject.class);
                for (JSONObject objects : jsonObjects) {
                    if(StringUtils.isNotEmpty(objects.getString("defaultValue"))){
                        form_data.put(object.getString("id"),objects.getString("name"));
                        form_info.put(object.getString("id"),objects.getString("name"));
                    }
                }
            }
            //========================单选属性匹配结束=====================//
        }
    }
    private void builderInputAttr(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, String inputAttr,Map<String,Object> form_data,Map<String,Object> form_info) {
//        JSONArray propertys = Objects.isNull(params.get("property")) ? new JSONArray() : JSONArray.parseArray(params.get("property").toString());
        Field[] declaredFields = goodsInfoAndAttrValueDto.getClass().getDeclaredFields();

        //========================开始匹配输入框=====================//
        JSONObject jsonObject1 = JSONObject.parseObject(inputAttr);
        String inputJson = jsonObject1.getString("inputJson");
        List<JSONObject> jsonObjects1 = JSONObject.parseArray(inputJson, JSONObject.class);
        GameAttrTemplate gameAttrTemplate = new GameAttrTemplate();
        gameAttrTemplate.setGameId(goodsInfoAndAttrValueDto.getGameId());
        gameAttrTemplate.setIsEnable("0");
        ArrayList types = new ArrayList<>();
        types.add("number");
        types.add("input");
        gameAttrTemplate.setFieldTypes(types);
        List<GameAttrTemplate> inputTemplates = gameAttrTemplateMapper.selectGameAttrTemplateList(gameAttrTemplate);
        List<JSONObject> defInputObjects = new ArrayList<>();
        defInputObjects.addAll(jsonObjects1);
        for (JSONObject object : jsonObjects1) {
            if(object.getString("id").equals("该游戏没有该匹配项 保存即可！")){
                return;
            }
            for (GameAttrTemplate inputTemplate : inputTemplates) {
                String string = "";
                String aavName = inputTemplate.getAavName();
                if (Objects.equals(object.getString("aavName"), inputTemplate.getAavName())) {
                    defInputObjects.remove(object);
                    String aavNameInter = object.getString("interName");
                    String interId = object.getString("interId");
                    for (Field declaredField : declaredFields) {
                        String name = declaredField.getName();
                        if (Objects.equals(aavName, name)) {
                            declaredField.setAccessible(true);
                            Object o = null;
                            try {
                                o = declaredField.get(goodsInfoAndAttrValueDto);
                            } catch (IllegalAccessException e) {
                                throw new GlobalException("3属性参数错误，请匹配后重新配置");
                            }
                            String oneValue = String.valueOf(o);
                            if (StringUtils.isNotEmpty(oneValue)) {
                                form_data.put(object.getString("id"),oneValue);
                                form_info.put(object.getString("id"),oneValue);
                            }
                        }
                    }
                }
            }
        }
        //开始匹配默认值
        for (JSONObject object : defInputObjects) {
            if(object.getString("name").equals("VIP等级")){
                if(goodsInfoAndAttrValueDto.getGameName().equals("枪战王者")){
                    if(StringUtils.isNotEmpty(goodsInfoAndAttrValueDto.getF2())){
                        GameAttribute gameAttribute1 = gameAttributeMapper.selectGameAttributeById(Long.valueOf(goodsInfoAndAttrValueDto.getF2()));
                        form_data.put(object.getString("id"),gameAttribute1.getFieldName().replace("V",""));
                        form_info.put(object.getString("id"),gameAttribute1.getFieldName().replace("V",""));
                    }
                }
            }else {
                String defaultValue = object.getString("defaultValue");
                if (StringUtils.isNotEmpty(defaultValue)) {
                    form_data.put(object.getString("id"), 0);
                    form_info.put(object.getString("id"), 0);
                }
            }
        }
    }


    private Map<String, Object> params(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto,SalePartner salePartner) {
        Map<String,Object> params = new HashMap<>();
        params.put("token",salePartner.getTwoOther());
        Map<String,Object> form_data = new HashMap<>();
        Map<String,Object> client_info = new HashMap<>();
        Map<String,Object> server_info = new HashMap<>();
        Map<String,Object> form_info = new HashMap<>();
        //自动匹配属性
        String substring = salePartner.getSaleName().substring(salePartner.getSaleName().indexOf("_")+1);
        InterAttr interAttr = interAttrMapper.selectInterAttrByConfig(substring, goodsInfoAndAttrValueDto.getGameId());
        params.put("game_id",interAttr.getInterGameId());
        builderServer(goodsInfoAndAttrValueDto, form_data,interAttr.getServer());
        form_data.put("title",goodsInfoAndAttrValueDto.getTitle().replace(" ","").replace("/","")
                .replace("|","").replace("-","").replace("·","")
                .replace("【","").replace("】","").replace("\n","")
                .replace("：","").replace("“","").replace("”","")
                .replace("\\",""));
        form_data.put("price",goodsInfoAndAttrValueDto.getPrice());
        GoodsInfoImg goodsInfoImg = new GoodsInfoImg();
        goodsInfoImg.setGoodsId(goodsInfoAndAttrValueDto.getId());
        goodsInfoImg.setType(Constants.STR_1);
        List<GoodsInfoImg> infoImgs = goodsInfoImgMapper.selectGoodsInfoImgList(goodsInfoImg);
        infoImgs = infoImgs.subList(0,1);
        List imgInfo = new ArrayList();
        for(GoodsInfoImg goodsInfoImg2 : infoImgs){
            String string = uploadImg(goodsInfoImg2.getImgUrl(),salePartner);
            imgInfo.add(string);
        }
        form_data.put("img_info",imgInfo);
        //开始匹配单选属性
        builderRadioAttr(goodsInfoAndAttrValueDto,interAttr.getRadioAttr(),form_data,form_info);
        //开始匹配多选属性
        builderCheckAttr(goodsInfoAndAttrValueDto,interAttr.getCheckAttr(),form_data,form_info);
        //开始匹配输入框属性
        builderInputAttr(goodsInfoAndAttrValueDto,interAttr.getInputAttr(),form_data,form_info);
        form_data.put("form_info",form_info);
        form_data.put("is_real",1);
        form_data.put("is_need_account",true);
        form_data.put("account", createQQAccount());
        form_data.put("qq_id",goodsInfoAndAttrValueDto.getAccountNumber());
        form_data.put("content",goodsInfoAndAttrValueDto.getDes().length()>200?goodsInfoAndAttrValueDto.getDes().substring(0,199):goodsInfoAndAttrValueDto.getDes());
        form_data.put("is_cut","1");
        form_data.put("shop_safe","1");
        form_data.put("es_price","0");
        form_data.put("is_recycle","1");
        form_data.put("phone",salePartner.getOther());
        params.put("form_data",form_data);
        params.put("img_data",imgInfo);
        params.put("id",0);
        params.put("pid",0);
        params.put("action",1);
        params.put("custcare_id",0);
        params.put("o_type",3);
        params.put("shop_type",0);
        params.put("shop_type_2",1);
        params.put("shop_since",1);
        params.put("is_rc_push",1);
        return params;
    }

    public static String createQQAccount() {
        int num = 8;
        String[] vec = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"};
        num = num <= 0 ? 1 : num;
        StringBuffer str = new StringBuffer(10);
        for (int i = 0; i < num; i++) {
            int r1 = Long.valueOf(Math.round(Math.random() * (vec.length - 1))).intValue();
            str.append(vec[r1]);
        }
        return str.toString();
    }

    @Override
    public AjaxResult delGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, SalePartner salePartner) {
        Map<String, Object> result = new HashMap<>();
        Map<String, Object> params = new TreeMap<>();
        params.put("token",salePartner.getTwoOther());
        ArtRec artRecreq = new ArtRec();
        artRecreq.setConfig(salePartner.getId());
        artRecreq.setAccountId(goodsInfoAndAttrValueDto.getId());
        List<ArtRec> artRecs = artRecMapper.selectArtRecList(artRecreq);
        ArtRec artRec = artRecs.get(0);
        params.put("shop_id", artRec.getOutid());
        params.put("type", "3");
        log.info("易手游编辑接口请求参数={}", JSONObject.toJSONString(params));
        String response = HttpRequest.post("https://www.swcbg.com/api/User/checkShopDown").body(JSONObject.toJSONString(params)).execute().body();
        log.info("易手游编辑接口返回参数={}", response);
        JSONObject resultJson = JSONObject.parseObject(response);
        if (!"1".equals(resultJson.getString("status"))) {
            result.put("code", 500);
        } else {
            result.put("code", 200);
            params = new TreeMap<>();
            params.put("token",salePartner.getTwoOther());
            params.put("shop_id", artRec.getOutid());
            String response2 = HttpRequest.post("https://www.swcbg.com/api/User/delShop").body(JSONObject.toJSONString(params)).execute().body();
            System.out.println(response2);
        }
        result.put("msg", resultJson.getString("info"));
        result.put("req", JSONObject.toJSONString(params));
        result.put("res", response);
        return AjaxResult.success(result);
    }

    public static void main(String[] args) {
        String urls = "https://www.swcbg.com/api/User/uploadShopImg";
        Map<String,Object> params = new HashMap<>();
        params.put("token","b1b2ba75a5871906f82020b1ef73d0e19bbe0bebc567d56fbbe83f3a98c449a87e95a8a01a96c267c47d25d97858b241728b4645bcdb84294c86a3a74455adfd945cccb1789cab7385ca1bd97daf9882c535666418c812d146214179c83cb8406a8a4346a16c98b5dfdccadf366a4353b19b84e0176d72511dfcad82e2f9aec6");
        String img = "https://imgv2.zuyoul.com/2c97e7c995d084260195d20958f50ad7.jpg";
        String string = DigestUtils.md5Hex(img);
        File file = null;
        try {
            URL url = new URL(img);
            BufferedImage image = ImageIO.read(url.openStream());
            byte[] bytes = ImgUntil.bufferedImageToByteArray(image);
            long srcSize = bytes.length;
            if (srcSize / 1024 > 5000) {
                bytes = ImgUntilYS.compressPicForScale(bytes, 3072l);
            } else {
                bytes = ImgUntilYS.compressPicForScale(bytes, 2048l);
            }
            file = convert(bytes,string);
        } catch (IOException e) {
            e.printStackTrace();
        }
        params.put("file",file);
        String body = HttpRequest.post(urls).form("token", "b1b2ba75a5871906f82020b1ef73d0e19bbe0bebc567d56fbbe83f3a98c449a87e95a8a01a96c267c47d25d97858b241728b4645bcdb84294c86a3a74455adfd945cccb1789cab7385ca1bd97daf9882c535666418c812d146214179c83cb8406a8a4346a16c98b5dfdccadf366a4353b19b84e0176d72511dfcad82e2f9aec6")
                .form("file", file).execute().body();
        String url2 = JSONObject.parseObject(body).getString("url");
        System.out.println(url2);
    }

    static String uploadImg(String img,SalePartner salePartner){
        String urls = "https://www.swcbg.com/api/User/uploadShopImg";
        Map<String,Object> params = new HashMap<>();
        params.put("token",salePartner.getTwoOther());
        String string = DigestUtils.md5Hex(img);
        File file = null;
        try {
            URL url = new URL(img);
            BufferedImage image = ImageIO.read(url.openStream());
            byte[] bytes = ImgUntil.bufferedImageToByteArray(image);
//            long srcSize = bytes.length;
//            if (srcSize / 1024 > 5000) {
//                bytes = ImgUntilYS.compressPicForScale(bytes, 3072l);
//            } else {
//                bytes = ImgUntilYS.compressPicForScale(bytes, 2048l);
//            }
            file = convert(bytes,string);
        } catch (IOException e) {
            e.printStackTrace();
        }
        params.put("file",file);
        String body = HttpRequest.post(urls).form("token", "b1b2ba75a5871906f82020b1ef73d0e19bbe0bebc567d56fbbe83f3a98c449a87e95a8a01a96c267c47d25d97858b241728b4645bcdb84294c86a3a74455adfd945cccb1789cab7385ca1bd97daf9882c535666418c812d146214179c83cb8406a8a4346a16c98b5dfdccadf366a4353b19b84e0176d72511dfcad82e2f9aec6")
                .form("file", file).execute().body();
        String url2 = JSONObject.parseObject(body).getString("url");
        return url2;
    }

    public static File convert(byte[] byteArray,String s) throws IOException {
        File file = File.createTempFile(s.substring(0,13), ".jpg");
//        imgUrl = file.getPath();
        Path path = Paths.get(file.getAbsolutePath());
        try (FileOutputStream fos = new FileOutputStream(file)) {
            fos.write(byteArray);
        }
        return file;
    }

}
